<?php
// filepath: /path/to/OAuth2.php

// 配置日志记录
$log_file = __DIR__ . '/logs/app.log';
if (!file_exists(__DIR__ . '/logs')) {
    mkdir(__DIR__ . '/logs', 0777, true);
}

function log_message($level, $message)
{
    global $log_file;
    $date = date('Y-m-d H:i:s');
    $log_entry = "[$date] $level: $message" . PHP_EOL;
    file_put_contents($log_file, $log_entry, FILE_APPEND);
}

// 获取请求参数
$code = $_GET['code'];

// 固定的client_id和client_secret
$client_id = '4628137f49914dc2';
$client_secret = '74e23ce3db7243bc8f853b04';

// 请求AccessToken的URL
$token_url = 'https://api.atomgit.com/login/oauth/access_token';

// 构建请求数据
$data = array(
    'client_id' => $client_id,
    'client_secret' => $client_secret,
    'code' => $code
);

// 初始化cURL会话
$ch = curl_init($token_url);

// 设置cURL选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

// 执行cURL请求
$response = curl_exec($ch);

// 检查cURL错误
if (curl_errno($ch)) {
    log_message('ERROR', 'cURL Error: ' . curl_error($ch));
    curl_close($ch);
    exit;
}

// 关闭cURL会话
curl_close($ch);

// 解析响应
$response_data = json_decode($response, true);
$access_token = $response_data['access_token'];
$refresh_token = $response_data['refresh_token'];

// 将access_token和refresh_token保存到数据库或其他存储中
// 这里假设有一个函数saveTokens来保存令牌
saveTokens($access_token, $refresh_token);

// 输出响应
header('Content-Type: application/json');
echo $response;

log_message('INFO', 'Access token and refresh token saved successfully.');

function saveTokens($access_token, $refresh_token) {
    // 实现保存令牌的逻辑，例如保存到数据库
    // 这里仅作示例
    file_put_contents("tokens.json", json_encode([
        'access_token' => $access_token,
        'refresh_token' => $refresh_token
    ]));
}
?>
